package com.name.givename.serviceimpl;

import com.name.givename.dao.UserInfoEntityMapper;
import com.name.givename.dao.UserNamedInfoEntityMapper;
import com.name.givename.dto.UserGiveNameDTO;
import com.name.givename.entity.UserInfoEntity;
import com.name.givename.entity.UserInformationEntity;
import com.name.givename.entity.UserNamedInfoEntity;
import com.name.givename.enums.ResultEnum;
import com.name.givename.exception.ServiceException;
import com.name.givename.param.GiveNameAddParams;
import com.name.givename.param.VoteNameParams;
import com.name.givename.result.ResultVoUtils;
import com.name.givename.service.GivenameAddService;
import com.name.givename.utils.Result;
import com.name.givename.utils.SensitiveWordFilter;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by yangtianrui on 18/9/2.
 */
@Service
public class GivenameAddServiceImpl implements GivenameAddService {

    @Autowired private UserNamedInfoEntityMapper userNamedInfoEntityMapper;
    @Autowired private UserInfoEntityMapper userInfoEntityMapper;
    private static final long ONE_DAY = 24 * 60 * 60 * 1000;
    List userIds = new ArrayList();

    /**
     * 用户起名
     * @param giveNameAddParams
     * @return
     */
    @Override
    public Result<List<String>> giveNameAdd(GiveNameAddParams giveNameAddParams) {

        if (giveNameAddParams.getOpenId() == null || giveNameAddParams.getPhone() == null) {
            throw new ServiceException(ResultEnum.GIVENAME_NULL.getCode(),ResultEnum.GIVENAME_NULL.getValue());
        }
        UserInformationEntity userInfo = userInfoEntityMapper.getUserInformationByOpenId(giveNameAddParams.getOpenId());
        if (userInfo != null && userInfo.getBindStatus().equals("0")) { // 未绑定 需要校验验证码
            // 验证码错误
            if (!userInfo.getPhoneCode().equals(giveNameAddParams.getPhoneCode())) {
                return ResultVoUtils.error(1,"对不起，验证码错误");
            }
        }
        SensitiveWordFilter filter = new SensitiveWordFilter();
        String [] giveNames = giveNameAddParams.getNameList();

        List<String> listNames = Stream.of(giveNames).collect(Collectors.toList());// 获取用户起名列表
        ArrayList resultNames = new ArrayList();
        listNames.stream().forEach((x)->{
            resultNames.add(filter.replaceSensitiveWord(x,1,"*"));
            System.out.println(resultNames.get(0));
        });
        UserNamedInfoEntity nameInfo = new UserNamedInfoEntity();
        resultNames.forEach(x->{
            nameInfo.setName(x.toString());
            if (nameInfo.getName() != null && nameInfo.getName().contains("**")) {
                throw new ServiceException(ResultEnum.NAME_IS_INVALID.getCode(),ResultEnum.NAME_IS_INVALID.getValue());
            }
            nameInfo.setOpenId(giveNameAddParams.getOpenId());
            nameInfo.setStatus("0");  //  审核状态为 1 默认通过
            nameInfo.setVoteCount(0);
            nameInfo.setAddTime(new Date());
            nameInfo.setUpdateTime(new Date());
            userNamedInfoEntityMapper.insert(nameInfo);
        }); //  list转为字符串 并用"，"分割

        if (giveNameAddParams.getNameList().length > 3) {
            throw new ServiceException(ResultEnum.ALLOW_THREE_NAMES.getCode(),ResultEnum.ALLOW_THREE_NAMES.getValue());
        }

        //  默认投票数量是 0
        return ResultVoUtils.success(resultNames);

    }

    /**
     * 用户投票
     * @param
     * @param
     * @return 目前票数
     */
    @Override
    public Result<UserGiveNameDTO> voteForNames(VoteNameParams voteNameParams) {
        if (voteNameParams.getNameId() == null || voteNameParams.getOpenId() == null) {
            throw new ServiceException(ResultEnum.NAME_ID_IS_NULL.getCode(),ResultEnum.NAME_ID_IS_NULL.getValue());
        }
        UserNamedInfoEntity userNamedInfoEntity = userNamedInfoEntityMapper.selectByPrimaryKey(voteNameParams.getNameId());
        //  用户自己不能给自己投票
        if(userNamedInfoEntity.getOpenId().equals(voteNameParams.getOpenId())) {
              return ResultVoUtils.error(1,"不能给自己投票!");
        }
        return ResultVoUtils.success(IncremVoteCount(userNamedInfoEntity,voteNameParams));
    }
    private synchronized Object IncremVoteCount(UserNamedInfoEntity entity,VoteNameParams voteNameParams) {
        long yesterdayTime = entity.getUpdateTime().getTime();
        int currentVoteCount = entity.getVoteCount();
        long validTime= yesterdayTime + ONE_DAY;// 算过期时间
        long currentTime = System.currentTimeMillis();
        if(currentTime < validTime && userIds.contains(voteNameParams.getOpenId())) {
            return ResultEnum.VOTETE_TIME_NOT_ALLOW.getValue();
        }
        userIds.remove(voteNameParams.getOpenId());
        entity.setVoteCount(currentVoteCount+1);
        entity.setUpdateTime(new Date());
        userNamedInfoEntityMapper.updateByPrimaryKey(entity);
        userIds.add(voteNameParams.getOpenId());
        return currentVoteCount+1;
    }


}
